package script.groovy

import cn.hutool.core.collection.CollectionUtil
import cn.net.sinodata.system.msghandler.parse.scripthandler.CommonScriptResult
import org.dom4j.Element

/**
 * 获取交易员信息
 * @param jsonResult
 * @return
 */
CommonScriptResult execute(Element parseResult) {

    Map<String, String> dataMap = new HashMap<>();

    // 获取side
    Element sideElement = (Element)parseResult.selectSingleNode("/message/body/Side");
    if (sideElement == null || !sideElement.hasContent()) {
        return CommonScriptResult.empty("Side节点值为空")
    }
    String side = sideElement.getText();

    // 获取NoPartyIDs
    List<Element> noPartyIDsRepeatGroup = (List<Element>)parseResult.selectNodes("/message/body/NoPartyIDs");
    if (CollectionUtil.isEmpty(noPartyIDsRepeatGroup) || noPartyIDsRepeatGroup.size() == 0) {
        return CommonScriptResult.empty("NoPartyIDs节点为空")
    }
    Element noPartyIDsElement = noPartyIDsRepeatGroup.get(1);
    List<Element> partyRoleElements = noPartyIDsElement.elements("PartyRole");
    List<Element> noPartySubIDsRepeatGroup = noPartyIDsElement.elements("NoPartySubIDs");

    for (int i=0; i<partyRoleElements.size(); i++) {
        String partyRole = partyRoleElements.get(i).getText();
        Element noPartySubIDsElement = noPartySubIDsRepeatGroup.get(i*2+1);
        List<Element>  PartySubIDElements = noPartySubIDsElement.elements("PartySubID");
        List<Element>  partySubIDTypeElements = noPartySubIDsElement.elements("PartySubIDType");
        if ((side == "1" && partyRole == "119") || (side == "4" && partyRole == "120")) { // 本方交易员相关信息
            for (int j=0; j<partySubIDTypeElements.size(); j++) {
                if (partySubIDTypeElements.get(j).getStringValue() == "101") {
                    String partySubID = PartySubIDElements.get(j).getStringValue()
                    dataMap.put("ourTraderName", partySubID);
                } else if (partySubIDTypeElements.get(j).getStringValue() == "126") {
                    String partySubID = PartySubIDElements.get(j).getStringValue()
                    dataMap.put("ourTraderNameCN", partySubID);
                }
            }
        } else if ((side == "1" && partyRole == "120") || (side == "4" && partyRole == "119")) { //对手方交易员相关信息
            for (int j=0; j<partySubIDTypeElements.size(); j++) {
                if (partySubIDTypeElements.get(j).getStringValue() == "102") {
                    String partySubID = PartySubIDElements.get(j).getStringValue()
                    dataMap.put("counterpartyOrgShortName", partySubID);
                } else if (partySubIDTypeElements.get(j).getStringValue() == "125") {
                    String partySubID = PartySubIDElements.get(j).getStringValue()
                    dataMap.put("counterpartyOrgShortNameCN", partySubID);
                }
            }
        }
    }
    return CommonScriptResult.success(dataMap);
}

